package com.mgg.payment.consumer;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import com.mgg.common.consumer.MessageConsumer;
import com.mgg.common.dto.CouponDTO;
import com.mgg.common.messaging.UserRegisterProcessor;
import com.mgg.common.payload.UserRegisterPayload;
import com.mgg.common.util.JsonUtils;
import com.mgg.payment.service.account.AccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class UserRegisterMessageConsumer implements MessageConsumer<UserRegisterPayload> {

	Logger log = LoggerFactory.getLogger(getClass());
	
	@Autowired
    private AccountService accountService;
	
    @StreamListener(UserRegisterProcessor.INPUT)
    @Transactional
	@Override
	public void receiveMessage(UserRegisterPayload payload) {
    	log.info("MQ【VIP注册】，payload = {}", JsonUtils.toJson(payload));
    	String userId = payload.getUserId();
//    	String refereeId = payload.getRefereeId();
    	try {
    		DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");	
    		LocalDateTime nowDateTime = LocalDateTime.now();

			CouponDTO coupon = accountService.getCouponByType("0","04");
    		accountService.insertUserCoupon(userId, coupon, 2, df.format(nowDateTime) + " 00:00:00");
		} catch (Exception e) {
			log.error("【VIP注册】，userId = {}", userId);
		}
	}
}
